<?php

namespace app\controller;

use app\model\OrderModel;
use app\model\OrderRefundModel;
use app\service\OrderService;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Support\XML;
use support\Db;
use support\facade\Logger;
use support\Request;
use const support\CORRECT;
use const support\DENY;
use const support\ERROR;
use const support\order_status_0;
use const support\order_status_1;
use const support\order_status_3;
use const support\order_status_8;
use const support\order_status_9;
use const support\refund_rule_1;
use const support\refund_rule_2;
use const support\refund_rule_5;

class PaymentCallBackController
{

    //微信异步通知
    public function wechatNotice(Request $request,$outTradeNo): \support\Response
    {
        Logger::app('微信订单支付异步通知：交易单号','info',$outTradeNo);
        $message = XML::parse(request()->rawBody());
        Logger::app('微信订单支付异步通知：请求数据','info',$message);
        if (empty($message['result_code']) || $message['result_code'] !== 'SUCCESS') {
            return wechatNotifySuccess();
        }
        //查询订单
        $order = OrderModel::where('order_trade_no',$message['out_trade_no'])->where('order_status',order_status_0)->first();

        if (empty($order->id)){
            Logger::app('微信订单支付异步通知：查询订单无效');
            return wechatNotifySuccess();
        }

        Db::beginTransaction();
        try {
            //保存分销数据
            $ret=OrderService::calculateDistributionCommission($order->id);
            if (!$ret){
                Db::rollBack();
                Logger::app('微信订单支付异步通知：保存分销数据错误');
                return wechatNotifyFail('保存分销数据错误');
            }
            // 更新订单信息
            $order->pay_time = time();
            $order->update_time=time();
            $order->order_status = CORRECT;
            $order->order_transaction_id=$message['transaction_id'];
            $ret=$order->save();
            if (!$ret){
                Db::rollBack();
                Logger::app('微信订单支付异步通知：订单更新失败');
                return wechatNotifyFail('订单支付结果错误');
            }
            //更新库存和销量
            $ret=OrderService::reduceStockNum($order->goods_id,$order->goods_period_id,$order->goods_num);
            if (!$ret){
                Db::rollBack();
                Logger::app('微信订单支付异步通知：订单更新库存和销量错误');
                return wechatNotifyFail('订单支付结果错误');
            }
            Db::commit();
            Logger::app('微信订单支付异步通知：支付成功');
            //处理完成之后，告诉微信成功结果
            return wechatNotifySuccess();
        } catch (\Throwable $e) {
            Db::rollBack();
            Logger::app($e);
            return wechatNotifyFail($e->getMessage());
        }
    }

    //微信订单退款异步通知
    public function wechatOrderRefundNotice(Request $request,$refundNo): \support\Response
    {
        Logger::app('微信订单退款异步通知：交易单号','info',[$refundNo]);
        Db::beginTransaction();
        try {
            $message = XML::parse(request()->rawBody());
            Logger::app('微信订单退款异步通知：请求数据','info',$message);
            $reqInfo=refundDecrypt($message['req_info']);
            $reqInfo=XML::parse($reqInfo);
            if (empty($reqInfo['refund_status'])){
                Logger::app('微信订单退款异步通知：解析出错','info',[$refundNo]);
                return wechatNotifyFail('微信订单退款异步通知解析出错');
            }
            Logger::app('微信订单退款异步通知：解密数据','info',$reqInfo);
            $update=[
                'update_time'       =>time(),
                'refund_recv_accout'=>$reqInfo['refund_recv_accout']
            ];
            if ($reqInfo['refund_status']!=='SUCCESS'){
                if ($reqInfo['refund_status']=='CHANGE'){
                    $failReason='退款异常';
                }else{
                    $failReason='退款关闭';
                }
                $update['fail_reason']=$failReason;
                $update['order_refund_status']=3;
                $isSuccess=DENY;
            }else{
                $update['refund_time']=strtotime($reqInfo['success_time']);
                $update['order_refund_status']=2;
                $isSuccess=CORRECT;
            }
            //更新订单退款信息
            $ret=OrderRefundModel::where([
                'order_refund_sn'       =>$refundNo,
            ])->update($update);
            if (!$ret){
                Db::rollBack();
                Logger::app('微信订单退款异步通知：更新失败');
                return wechatNotifyFail('微信订单退款状态更新失败');
            }
            if ($isSuccess==CORRECT){
                //获取订单ID
                $orderRefund=OrderRefundModel::where([
                    'order_refund_sn'       =>$refundNo,
                ])->select(['order_id','order_deduction_type'])->first()->toArray();
                if (in_array($orderRefund['order_deduction_type'],[refund_rule_1,refund_rule_2,refund_rule_5])){
                    $isRefund=3;
                }else{
                    $isRefund=4;
                }
                //更新订单信息
                $ret=OrderModel::where([
                    'id'=>$orderRefund['order_id']
                ])->update([
                    'is_refund'     =>$isRefund,
                    'refund_time'   =>time(),
                    'order_status'  =>order_status_9,
                    'update_time'   =>time()
                ]);
                if (!$ret){
                    Db::rollBack();
                    Logger::app('微信订单退款异步通知：订单状态更新失败');
                    return wechatNotifyFail('微信订单退款状态更新失败');
                }
                Logger::app('微信订单退款异步通知：退款成功','info',[$refundNo]);
            }else{
                Logger::app('微信订单退款异步通知：退款失败','info',[$refundNo]);
            }
            Logger::app('微信订单退款异步通知：退款处理完成','info',[$refundNo]);
            Db::commit();
            return wechatNotifySuccess();
        }catch (\Throwable $e){
            Db::rollBack();
            Logger::app($e);
            return wechatNotifyFail($e->getMessage());
        }
    }
}